﻿<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Data;
using GMS.Utils;
using Maticsoft.DBUtility;
using System.Web.SessionState;
using GMS.Model;
using System.Collections;
using GMS.Web.AppOperation;

public class Handler : IHttpHandler, IRequiresSessionState {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        DataTable modelDt = null;
        GMS.Model.User user = (GMS.Model.User)context.Session["_User"];
        if (context.Session["_User"] == null)
       {
           context.Response.Write("<script language='javascript'>top.location.href='" + context.Request.ApplicationPath + @"/login.aspx';</script>");
           return;
       }
        modelDt = ApplicationOperation.GetUserModuleList(user.IndexID);
        if (modelDt == null)
        {
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                //modelDt = new GMS.BLL.SysFunModuleAccessBLL().GetAllList();
                //if (context.Session["_User"] == null)
                //{
                //    context.Response.Write("<script language='javascript'>top.location.href='" + context.Request.ApplicationPath + @"/login.aspx';</script>");
                //    return;
                //}
                //GMS.Model.User user = (GMS.Model.User)context.Session["_User"];
                modelDt = new GMS.BLL.SysFunModuleAccessBLL().GetUserModuleList(user);
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
                modelDt = new GMS.BLL.SysFunModuleBLL().GetAllList();
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                //modelDt = new GMS.BLL.SysFunModuleAccessBLL().GetAllList();
                //if (context.Session["_User"] == null)
                //{
                //    context.Response.Write("<script language='javascript'>top.location.href='" + context.Request.ApplicationPath + @"/login.aspx';</script>");
                //    return;
                //}
                //GMS.Model.User user = (GMS.Model.User)context.Session["_User"];
                modelDt = new GMS.BLL.SysFunModuleOraBLL().GetUserModuleList(user);
            }
            else
                return;
            ApplicationOperation.SetUserModuleList(user.IndexID, modelDt);
        }
        String rs = getJson(modelDt);
        context.Response.Write(rs);
        //context.Response.Write("[ { text:'数据管理',children:[{ text:'帐户信息',leaf:'true'},{ text:'字段管理',leaf:'true'},{ text:'用户管理',leaf:'true'},{ text:'模块管理',leaf:'true'},{ text:'系统环境',leaf:'true'},{ text:'角色管理',leaf:'true'},{ text:'类型参数',leaf:'true'}]},{ text:'系统管理',children:[{ text:'帐户信息',leaf:'true'},{ text:'字段管理',leaf:'true'},{ text:'用户管理',leaf:'true'},{ text:'模块管理',leaf:'true'},{ text:'系统环境',leaf:'true'},{ text:'角色管理',leaf:'true'},{ text:'类型参数',leaf:'true'}]}]");
        //context.Response.Write("[ { text:'旅店信息',leaf:true,href:'../Public/CommonPage.aspx?table=tab_hotel',hrefTarget:'ContFrame'},{ text:'数据管理',leaf:false,children:[{ text:'基础数据管理',leaf:false,children:[{ text:'医院信息',leaf:true,href:'../Public/CommonPage.aspx?table=tab_hospital',hrefTarget:'ContFrame'},{ text:'校园信息2',leaf:true,href:'../public/CommonPage.aspx?table=v_schoolinfo',hrefTarget:'ContFrame'},{ text:'校园信息',leaf:true,href:'../Public/CommonPage.aspx?table=tab_schoolinfo',hrefTarget:'ContFrame'},{ text:'test23',leaf:true,href:'../System/user/UserManager.aspx',hrefTarget:'ContFrame'},{ text:'学生',leaf:true,href:'../Public/CommonPage.aspx?table=tab_student',hrefTarget:'ContFrame'}]}]},{ text:'人才管理',leaf:false,children:[{ text:'人才信息',leaf:true,href:'../public/CommonPage.aspx?table=Tab_HumanRes',hrefTarget:'ContFrame'},{ text:'客户信息',leaf:true,href:'../public/CommonPage.aspx?table=Tab_CustomerInfo',hrefTarget:'ContFrame'},{ text:'寻访信息',leaf:true,href:'../public/CommonPage.aspx?table=Tab_SearchInfo',hrefTarget:'ContFrame'},{ text:'岗位信息',leaf:true,href:'../public/CommonPage.aspx?table=Tab_JobInfo',hrefTarget:'ContFrame'},{ text:'岗位进度信息',leaf:true,href:'../public/CommonPage.aspx?table=Tab_JobSta',hrefTarget:'ContFrame'}]},{ text:'入库管理',leaf:false,children:[{ text:'物品入库',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'物品退库',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'采购计划',leaf:true,href:'',hrefTarget:'ContFrame'}]},{ text:'库存管理',leaf:false,children:[{ text:'库存明细',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'库存调拨',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'库存报警',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'库存报损',leaf:true,href:'',hrefTarget:'ContFrame'}]},{ text:'销售管理',leaf:false,children:[{ text:'销售出库',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'销售退货',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'销售收款',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'产品报废',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'销售计划',leaf:true,href:'',hrefTarget:'ContFrame'}]},{ text:'统计报表',leaf:false,children:[{ text:'入库报表',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'库存报表',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'出库报表',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'退货报表',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'报废报表',leaf:true,href:'',hrefTarget:'ContFrame'}]},{ text:'参数管理',leaf:false,children:[{ text:'计量单位管理',leaf:true,href:'',hrefTarget:'ContFrame'},{ text:'客户管理',leaf:true,href:'../System/user/UserManager.aspx',hrefTarget:'ContFrame'},{ text:'供应商管理',leaf:true,href:'',hrefTarget:'ContFrame'}]},{ text:'系统管理',leaf:false,children:[{ text:'角色管理',leaf:true,href:'../System/Role/RoleManager.aspx',hrefTarget:'ContFrame'},{ text:'帐户信息old',leaf:true,href:'../System/user/UserManagerDetails.aspx?tablecode=TAB_USER&cdtion=',hrefTarget:'ContFrame'},{ text:'用户管理2',leaf:true,href:'../public/CommonPage.aspx?table=TAB_USER',hrefTarget:'ContFrame'},{ text:'用户管理',leaf:true,href:'../Public/CommonPage.aspx?table=tab_user',hrefTarget:'ContFrame'},{ text:'模块管理',leaf:true,href:'../System/Module/ModuleManager.aspx',hrefTarget:'ContFrame'},{ text:'系统环境',leaf:true,href:'../System/SysConfig/SysEnvConfig.aspx',hrefTarget:'ContFrame'},{ text:'类型参数',leaf:true,href:'../System/TypePara/TypeParameter.aspx?table=',hrefTarget:'ContFrame'},{ text:'用户管理old',leaf:true,href:'../System/user/UserManager.aspx?table=TAB_USER',hrefTarget:'ContFrame'},{ text:'字段管理',leaf:true,href:'../Public/ColumnsManager.aspx',hrefTarget:'ContFrame'},{ text:'帐户信息',leaf:true,href:'../public/CommonPageDetails.aspx?tablecode=TAB_USER&cdtion=',hrefTarget:'ContFrame'}]},{ text:'数据录入',leaf:false,children:[{ text:'excel导入',leaf:true,href:'../ExcelImport/Default.aspx',hrefTarget:'ContFrame'},{ text:'模板管理',leaf:true,href:'../ExcelImport/TemplateManage.aspx',hrefTarget:'ContFrame'}]}]");
    }
    
    /// <summary>
    /// 获取左侧树对应的字符串
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    private String getJson(DataTable data) 
    {
        List<SysFunModule> list = new List<SysFunModule>();
        for(int i=0;i<data.Rows.Count;i++)
        {
            SysFunModule sfm = new SysFunModule();
            sfm.TABSYSID = Int32.Parse(data.Rows[0].Table.Rows[i]["TABSYSID"].ToString());
            sfm.MODULESEQ = Int32.Parse(data.Rows[0].Table.Rows[i]["MODULESEQ"].ToString());
            sfm.MODULENAME = data.Rows[0].Table.Rows[i]["MODULENAME"].ToString();
            sfm.URL = data.Rows[0].Table.Rows[i]["URL"].ToString();
            sfm.ISUNFOLD = Int32.Parse(data.Rows[0].Table.Rows[i]["ISUNFOLD"].ToString());
            sfm.FATHERMODULEID =data.Rows[0].Table.Rows[i]["FATHERMODULEID"].ToString()== "" ? -1 : Int32.Parse(data.Rows[0].Table.Rows[i]["FATHERMODULEID"].ToString());
            list.Add(sfm);
        }
        HashSet<int> parentset = new HashSet<int>();
        
        List<List<SysFunModule>> plist = new List<List<SysFunModule>>();
        int number = getDepth(list);
        for (int i = 0; i < number; i++)
        {
            plist.Add(new List<SysFunModule>());
            for (int j = 0; j < list.Count; j++) 
            {
                if (i == 0) 
                {                    
                    if (list[j].FATHERMODULEID == -1)
                        plist[i].Add(list[j]);
                }
                else 
                { 
                    bool flag = false;
                    for(int k=0;k<plist[i-1].Count;k++)
                    {
                        if (list[j].FATHERMODULEID == plist[i - 1][k].TABSYSID) 
                        { 
                            parentset.Add(plist[i - 1][k].TABSYSID); 
                            flag = true; 
                            break; 
                        }
                    }
                    if (flag == true) 
                    { 
                        plist[i].Add(list[j]); 
                    }
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.Append("[ ").Append(getChildrenJson(plist, 0, -1,parentset)).Append("]");
        return sb.ToString();
    
    }
    
    /// <summary>
    /// 获取子树
    /// </summary>
    /// <param name="plist"></param>
    /// <param name="depth"></param>
    /// <param name="fatherid"></param>
    /// <param name="parentset"></param>
    /// <returns></returns>
    private String getChildrenJson(List<List<SysFunModule>> plist, int depth, int fatherid, HashSet<int> parentset)
    {
        if (plist.Count <=depth) return "";
        int num = plist[depth].Count;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < num; i++) 
        {
            if (plist[depth][i].FATHERMODULEID == fatherid)
            {
                if (!parentset.Contains(plist[depth][i].TABSYSID))
                {//叶子节点
                    String url = plist[depth][i].URL.ToString();
                    String newurl = url.Replace("~", "..");
                    sb.Append("{ text:'").Append(plist[depth][i].MODULENAME.ToString()).Append("',leaf:true,").Append("href:'").Append(newurl).Append("',hrefTarget:'ContFrame'},");
                }
                else //非叶子节点
                {
                    if(plist[depth][i].ISUNFOLD == 1)//展开
                        sb.Append("{ text:'").Append(plist[depth][i].MODULENAME.ToString()).Append("',leaf:false,expanded:true,children:[").Append(getChildrenJson(plist, depth + 1, (int)plist[depth][i].TABSYSID, parentset)).Append("]},");
                    else //不展开
                        sb.Append("{ text:'").Append(plist[depth][i].MODULENAME.ToString()).Append("',leaf:false,expanded:false,children:[").Append(getChildrenJson(plist, depth + 1, (int)plist[depth][i].TABSYSID, parentset)).Append("]},");
                }
                
            }
        }
        String str = sb.ToString().Substring(0, sb.Length - 1);
        return str;
    }
    
    /// <summary>
    /// 获取树的深度
    /// </summary>
    /// <param name="list"></param>
    /// <returns></returns>
    private int getDepth(List<SysFunModule> list)
    {
        //树的深度
        List<SysFunModule> usedlist = new List<SysFunModule>();
        int depth = 0;
        if (list.Count == 0) return 0;
        int lastindex = 0;
        while (usedlist.Count != list.Count) 
        {            
            //增加下面几行代码是防止死循环
            //死循环发生在有些模块没有父节点的时候
            //lastindex == usedlist.Count表示和上次相比，没有增加，那么说明剩下的都是无父节点的
            if (lastindex == usedlist.Count && lastindex != 0)
            {
                depth--;
                break;
            }
            //
            
            
            int lastlastindex = lastindex;
            lastindex = usedlist.Count;//用过的（判断过了）
            if (lastindex == 0) //第一次遍历一下，所有顶级的都放在usedlist中
            {
                for (int i = 0; i < list.Count; i++)//读完后，顶级的都在中了。
                {
                    if (list[i].FATHERMODULEID == -1) //顶级的
                        usedlist.Add(list[i]);
                }
            }
            else
            {
                for (int i = lastlastindex; i < lastindex; i++)
                {
                    for (int j = 0; j < list.Count; j++)
                    {
                        if (list[j].FATHERMODULEID == usedlist[i].TABSYSID) 
                            usedlist.Add(list[j]); 
                    } 
                }
            }
            depth++;
        }
        return depth;
    }
    public bool IsReusable 
    {
        get 
        {
            return false;
        }
    }

}